package com.hongtech.tiny.modules.sys.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hongtech.tiny.modules.sys.entity.SysResource;
import com.hongtech.tiny.modules.sys.mapper.SysResourceMapper;
import com.hongtech.tiny.modules.sys.service.SysAdminCacheService;
import com.hongtech.tiny.modules.sys.service.SysResourceService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 后台资源管理Service实现类
 */
@Service
@RequiredArgsConstructor
public class SysResourceServiceImpl extends ServiceImpl<SysResourceMapper, SysResource>implements SysResourceService {

    private final SysAdminCacheService adminCacheService;

    @Override
    public boolean create(SysResource sysResource) {
        sysResource.setCreateTime(new Date());
        return save(sysResource);
    }

    @Override
    public boolean update(Long id, SysResource sysResource) {
        sysResource.setId(id);
        boolean success = updateById(sysResource);
        adminCacheService.delResourceListByResource(id);
        return success;
    }

    @Override
    public boolean delete(Long id) {
        boolean success = removeById(id);
        adminCacheService.delResourceListByResource(id);
        return success;
    }

    @Override
    public Page<SysResource> list(Long categoryId, String nameKeyword, String urlKeyword, Integer pageSize, Integer pageNum) {
        Page<SysResource> page = new Page<>(pageNum,pageSize);
        QueryWrapper<SysResource> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<SysResource> lambda = wrapper.lambda();
        if(categoryId!=null){
            lambda.eq(SysResource::getCategoryId,categoryId);
        }
        if(StringUtils.isNotEmpty(nameKeyword)){
            lambda.like(SysResource::getName,nameKeyword);
        }
        if(StringUtils.isNotEmpty(urlKeyword)){
            lambda.like(SysResource::getUrl,urlKeyword);
        }
        return page(page,wrapper);
    }
}
